package com.imu.purse.modules.app.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imu.core.base.BaseService;
import com.imu.purse.modules.app.dao.TokenMapper;
import com.imu.purse.modules.app.entity.TokenEntity;
import com.imu.purse.modules.app.service.TokenService;
import java.util.Date;
import java.util.UUID;

@Service("tokenService")
public class TokenServiceImpl extends BaseService<TokenEntity> implements TokenService
{
	/**
	 * 12小时后过期
	 */
	private final static int EXPIRE = 3600 * 12;

	@Override
	public TokenEntity queryByToken(String token) 
	{
		TokenEntity entity = new TokenEntity();
		entity.setToken(token);
		return mapper.selectOne(entity);
	}

	@Override
	public TokenEntity createToken(long userId) {
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//生成token
		String token = generateToken();

		//保存或更新用户token
		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);

		return tokenEntity;
	}

	@Override
	public void expireToken(long userId){
		Date now = new Date();

		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(now);
	}

	private String generateToken(){
		return UUID.randomUUID().toString().replace("-", "");
	}
	

	@Autowired
	private TokenMapper mapper;
}
